package com.xiaoyaoji.txt.util;

import com.alibaba.fastjson.JSONObject;
import com.xiaoyaoji.admin.pojo.dto.HttpDoc;
import com.xiaoyaoji.admin.pojo.dto.HttpDocEntity;
import com.xiaoyaoji.txt.pojo.dto.TxtDTO;

import java.util.ArrayList;
import java.util.List;

public class DocUtils {

    /**
     * 获取请求内容
     */
    public static String getDocContent(TxtDTO txtDTO) {

        HttpDoc httpDoc = new HttpDoc();
        httpDoc.setRequestMethod(txtDTO.getRequestMethod());
        String dataType = "GET".equalsIgnoreCase(txtDTO.getRequestMethod()) ? "X-WWW-FORM-URLENCODED" : "JSON";
        httpDoc.setDataType(dataType);
        httpDoc.setStatus("有效");
        httpDoc.setContentType("JSON");
        httpDoc.setUrl(txtDTO.getUrl());


        //请求参数
        List<HttpDocEntity> requestArgs = new ArrayList<>();
        List<TxtDTO.Property> requestProperties = txtDTO.getRequest().getChildrenProperties();
        setRequestAndResponse(requestArgs, requestProperties);
        httpDoc.setRequestArgs(requestArgs);

        //响应参数
        List<HttpDocEntity> responseArgs = new ArrayList<>();
        List<TxtDTO.Property> responseProperties = txtDTO.getResponse().getChildrenProperties();
        setRequestAndResponse(responseArgs, responseProperties);
        httpDoc.setResponseArgs(responseArgs);

        return JSONObject.toJSONString(httpDoc);
    }

    private static void setRequestAndResponse(List<HttpDocEntity> children, List<TxtDTO.Property> properties) {
        if (properties != null && properties.size() > 0) {
            for (TxtDTO.Property property : properties) {
                HttpDocEntity entity = new HttpDocEntity();
                entity.setName(property.getName());
                entity.setType(property.getType());
                entity.setRequire("false");
                entity.setDescription(property.getDescription());
                ergodicParameters(entity, property.getChildrenProperties());
                children.add(entity);
            }
        }
    }

    private static void ergodicParameters(HttpDocEntity httpDocEntity, List<TxtDTO.Property> properties) {
        if (properties == null || properties.size()==0) return;
        List<HttpDocEntity> childrenList = new ArrayList<HttpDocEntity>();
        setRequestAndResponse(childrenList, properties);
        httpDocEntity.setChildren(childrenList);
    }
}
